import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 客户端
 */
public class UDPEchoClient {
    //声明客户端对象
    private DatagramSocket socket;
    //声明IP
    private String severIP;
    //声明要访问的端口号
    private int severPort;
    //创建客户端对象
    public UDPEchoClient(String severIP,int severPort) throws SocketException {
        this.severIP = severIP;
        this.severPort = severPort;
        socket = new DatagramSocket();
    }
    //处理客户端服务
    public void start() throws IOException {
        System.out.println("服务端已开启...");
        //循环处理数据
        while (true) {
            //请求用户输入
            System.out.println("请输入要求：");
            System.out.print("->");
            Scanner scanner = new Scanner(System.in);
            String request = scanner.nextLine();
            if(request == null || request.isEmpty()) {
                System.out.println("不能输入空字符串...");
                continue;
            }
            //创建端口号 IP 对象
            InetSocketAddress address = new InetSocketAddress(severIP, severPort);
            //创建用于传输的DatagramPacket对象
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0,request.length(),address);
            //上传给服务端
            socket.send(requestPacket);

            //创建接收 存储 服务器返回的数据的对象
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            //接收服务器返回的数据
            socket.receive(responsePacket);
            //解析返回的数据
            String response = new String(responsePacket.getData(),0,
                    responsePacket.getLength(),"UTF-8");
            //打印相应结果
            System.out.printf("request = %s,response = %s",request,response);
            System.out.println();
        }
    }

    public static void main(String[] args) throws IOException {
        UDPEchoClient udpEchoClient = new UDPEchoClient("192.168.31.175",8888);
        udpEchoClient.start();
    }
}
